package net.jxta.myjxta.util.configuration;

import net.jxta.myjxta.util.ConfigurationView;
import net.jxta.myjxta.util.Env;
import net.jxta.platform.NetworkConfigurator;
import net.jxta.platform.NetworkManager;

import java.io.IOException;
import java.util.logging.Logger;

public class NetworkManagerConfigurator implements MyJXTAConfigurator {

    private static final Logger LOG = Logger.getLogger(NetworkManagerConfigurator.class.getName());

    private ConfigurationView m_view = null;
    private String m_instanceName;

    private String m_descripton;
    private String m_identityName;
    private String m_password;

    public NetworkManagerConfigurator(ConfigurationView p_p_view) {
        this.m_view = p_p_view;

    }

    public boolean configurePlatform() throws IOException {
        NetworkConfigurator configurator = new NetworkConfigurator(NetworkConfigurator.EDGE_NODE, Env.getHome());

        if (configurator.exists())
            return true; //allready configured;

        boolean viewSuccessFull = m_view.configure(new MyPlatformConfigAccess());
        if (viewSuccessFull) {
            NetworkManager networkManager = new NetworkManager(NetworkManager.ConfigMode.EDGE, m_instanceName, Env.getHome());
            networkManager.setUseDefaultSeeds(true);
            networkManager.setConfigPersistent(true);

            configurator = networkManager.getConfigurator();
            configurator.setPrincipal(m_identityName);
            configurator.setDescription(m_descripton);
            configurator.setPassword(m_password);
            configurator.save();
            return true;
        } else {
            return false;
        }


    }

    private class MyPlatformConfigAccess implements ConfigurationView.PlatformConfigAccess {

        public void setName(String p_name) {
            m_instanceName = p_name;
        }

        public void setDescription(String p_version) {
            m_descripton = p_version;
        }

        public void setSecurity(String p_name, String p_password) {
            m_identityName = p_name;
            m_password = p_password;
        }
    }

}